package com.anteater.eattheant;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.Button;

import com.anteater.eattheant.util.Ranking;

public class LevelActivity extends Activity {
	
	private AbsoluteLayout layout;
	
    public static final int NUMBER_LEVELS = 15;
    private final int FRACTION_LEVELS = 3;
    
    private final int SPACE_Y = 90;
    private final int SPACE_X = 210;
    
    private final int INITIAL_Y = 8;
    private final int INITIAL_X = 170;
    
    private final int HEIGHT = 170;
    private final int WIDTH = 90;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    	
    	setContentView(R.layout.level);
    	
    	//FIXME procurar solução para o layout Deprecated
    	layout = (AbsoluteLayout) findViewById(R.id.absoluteLayout);
    	createButtons();
    }

	private void createButtons() {
		Ranking ranking = new Ranking(this);
    	
    	int count = 0;
    	int x = INITIAL_X;
    	int y = INITIAL_Y;
        
    	for (int i = 0; i < NUMBER_LEVELS; i++) {
    		
    		final int level = i;
        	Button b = new Button(this);
        	b.setText("Level " + (i+1));
        	b.setLayoutParams(new AbsoluteLayout.LayoutParams(HEIGHT, WIDTH, x, y));
        	
        	b.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getBaseContext(), PlayActivity.class);
	                intent.putExtra("level", level);
	                startActivity(intent);
				}
			});

        	if (i <= ranking.getMaxLevel()) {
        		b.setTextColor(Color.GREEN);
        		if (ranking.getScore(i+1) != null) {
        			b.setText("Level " + (i+1) + "\n Score: " + ranking.getScore(i+1).getScore());
        		}
        	} else {
        		b.setTextColor(Color.RED);
        		b.setClickable(false);
        	}

        	layout.addView(b);

        	// dynamically position
        	count = (count+1) % FRACTION_LEVELS;
        	x = x + SPACE_X;
        	if (count == 0) {
        		x = INITIAL_X;
        		y = y + SPACE_Y;
        	}
        }
	}
    
    @Override
    protected void onStart() {
    	super.onStart();
    	layout.removeAllViews();
    	createButtons();
    }
}
